<?php

/**
 * Impress - Open source digital signage
 *
 * @link http://digitalsignage.tk
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Impress
 * @package Impress
 */

/**
 * This class can be used for routing requests in application.
 *
 * @package Impress
 * @subpackage Core
 */

class ADS_Navigator {
    
    private static $isFreezed = false;
    
    static function parseTarget($target){
        //validate smart URL and extract values 
        if($target != 'self' && !preg_match('/^([a-zA-Z]+):([a-zA-Z]+)$/',$target,$extract)){
            return false;
        }
        return array(
            'page'   => $extract[1] == 'self'?$_GET['page']:$extract[1],
            'action' => $extract[2]
        );
    }
    
    static function getURL($target, $variables = array(), $append = '',$escape = false){

        //validate smart URL and extract values 
        if($target != 'self' && !preg_match('/^([a-zA-Z]+):([a-zA-Z]+)$/',$target,$extract)){
            return false;
        }
        //basic URL
        $page = $extract[1] == 'self'?$_GET['page']:$extract[1];
        $url = sprintf(
            _ifset(
                $extract[2] == 'defaultAction', 
                $_SERVER['SCRIPT_NAME'] . '?page=%s', 
                $_SERVER['SCRIPT_NAME'] . '?page=%s&do=%s'
            ),
            $page,
            $extract[2]
        );        
        //add variables from request
        foreach (explode(',',$append) as $variable) {
            if(isset($_REQUEST[$variable])){
                $variables[$variable] = $_REQUEST[$variable];
            }
        }
        //generate security token?
        if(isset($variables['token']) && $variables['token'] === 'true'){
            $variables['token'] = wp_create_nonce($page.':'.$extract[2]);
        }
        //append query to basic URL
        $query = http_build_query($variables);
        if(strlen($query) > 0)
            $url .= '&'.$query;

        return $escape?esc_url($url):$url;
    }
    
    static function redir($target, $variables = array(), $append = ''){

        if(!headers_sent() && !self::$isFreezed){
            header('location:' . self::getURL($target, $variables, $append));
            exit;
        }
        
    }
    
    static function freeze(){
        self::$isFreezed = true;
    }
    
    static function unfreeze(){
        self::$isFreezed = false;
    }
}
